function out = get_context_hist(im, pos, target_sz, factor)
%get 16x16x16 RGB color histogram in the ROI factor*factor times larger
%than the target
    out = zeros(1,4096);
    sz = target_sz * factor;
    xs = floor(pos(2)) + (1:sz(2)) - floor(sz(2)/2);
    ys = floor(pos(1)) + (1:sz(1)) - floor(sz(1)/2);
    
    %check for out-of-bounds coordinates, and set them to the values at
    %the borders
    xs(xs < 1) = 1;
    ys(ys < 1) = 1;
    xs(xs > size(im,2)) = size(im,2);
    ys(ys > size(im,1)) = size(im,1);
    
    context_patch = im(ys, xs, :);
    
    context_height = size(context_patch,1);
    context_width = size(context_patch,2);
    
    w_sum = 0;
    
    for y=1:context_height
        for x=1:context_width
            rv = floor(double(context_patch(y,x,1))/16);
            gv = floor(double(context_patch(y,x,2))/16);
            bv = floor(double(context_patch(y,x,3))/16);
            color_index = rv*256 + gv*16 + bv + 1;
            out(1,color_index) = out(1, color_index)+1;
            w_sum = w_sum+1;
        end
    end
    
    out = out ./ w_sum;
end

